package com.test.application.bidirectional_linked_list;

import lombok.Getter;

//遍历链表
public class DoublyLinkedListTraversal {
    private DoublyLinkedListNode head;
    @Getter
    private DoublyLinkedListNode tail;
    // 添加到链表头部
    public void addFirst(int data) {
        DoublyLinkedListNode newNode = new DoublyLinkedListNode(data);

        if (head == null) {
            head = newNode;
            tail = newNode;
        } else {
            newNode.next = head;
            head.prev = newNode;
            head = newNode;
        }
    }
    //正向遍历
    public void traverseForward() {
        DoublyLinkedListNode current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println(); // 换行
    }

    // 添加其他方法，如添加、删除节点等


    //反向遍历
    public void traverseBackward() {
        if (head == null) return; // 如果链表为空则直接返回

        DoublyLinkedListNode current = head;
        while (current.next != null) {
            current = current.next;
        }

        while (current != null) {
            System.out.print(current.data + " ");
            current = current.prev;
        }
        System.out.println(); // 换行
    }
    public static void main(String[] args) {
        DoublyLinkedListTraversal list = new DoublyLinkedListTraversal();

        // 假设我们已经有一些添加节点的方法，这里是模拟数据
        list.addFirst(1);
        list.addFirst(2);
        list.addFirst(3);

        System.out.println("Traversing forward:");
        list.traverseForward();

        System.out.println("Traversing backward:");
        list.traverseBackward();
    }

}